<?php
namespace Admin\Controller;

require_once './ThinkPHP/Library/Vendor/qiniuyun/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class IndexController extends BaseController {
    public function panelData(){
        $begin = strtotime(date('Y-m-d',time()).' 00:00:00');
        $end = strtotime(date('Y-m-d',time()).' 23:59:59');
        $condition['add_time'] = array('between',"$begin,$end");
        $condition['pay_code'] = 'cod';
        // $panel_data = F('gd_panel_data');
        // if(!$panel_data){
            $panel_data = update_panel_data();
        // }
        dump($panel_data);

        // $model = new Model();
        // $csj_db = $model->db('2',"mysql://tlcgp:AWzrhCa8fJ@139.9.50.10:3306/csj_shop");
        // $csj_order_count = $csj_db->table('ty_order')->where($condition)->count();
        // dump($order_count);
        // dump($csj_order_count);
    }
   public function cs(){
        $goods_category = M('goods_category')->where(['image'=>['neq','']])->select();


        function downloadImage($url,$fromPlatUrl)
        {
            $url = $fromPlatUrl.$url;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            $file = curl_exec($ch);
            curl_close($ch);
            saveAsImage($url, $file);
        }

        function saveAsImage($url, $file)
        {

            $filename = pathinfo($url, PATHINFO_BASENAME);
            $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME);
            $path =   substr($dirname,1);
            $fullpath =  $path . '/' . $filename;


            // 如果目录不存在，则创建
            if(!is_dir($path)) {
                mkdir($path, 0777, true);
            }
           
            if(file_exists($fullpath)) {
               
            }else{
                $resource = fopen($fullpath, 'a');
                fwrite($resource, $file);
                fclose($resource);
            }
        }
        foreach ($goods_category as $value){
            $fullpath =  substr($value['image'],1);
         
            if(file_exists($fullpath)) {
                continue;
            }
          
            downloadImage($value['image'],'https://cdngy.zczmer.com'); //下载大图
        }

	}


   public function pp(){ //遍历溢价
 	$order_list=M('order')->where('add_time>1669880215 and add_time<'.\time())->select();
	
 		foreach($order_list as $v){
			$order_goods=M('order_goods')->where('order_id='.$v['order_id'])->order('yijia desc')->getField('yijia');
			if($order_goods==0 && $v['yijia_heji']!=0){
				M('order')->where('order_id='.$v['order_id'])->setField(['yijia_heji'=>0]);
				echo $v['order_sn'].'：'.'yijia:'.$v['yijia_heji'].'<br/>';
			}
			
		}
     }
	 
	 // public function jj(){ //重写产品销售数量 
		// $userlist=M('users')->where('pay_points<100')->select();
		// foreach($userlist as $v){
		// 	$jifen=M('order')->where('user_id='.$v['user_id'].' and order_status in(0,1,2) and add_time<1661961600')->sum('order_amount');
		// 	$jifens=$jifen ? $jifen : 0;
		// 	M('users')->where('user_id='.$v['user_id'])->setInc('pay_points',$jifens);
		// }
		
	 //   }
 public function dd(){ 
     
     $seller=M('store')->select();
     foreach ($seller as $v){
         $gongs=explode('（',$v['seller_name']);$gongs1=str_replace(')','',$gongs[1]);
         M('users')->where('user_id='.$v['user_id'])->setField(['company'=>$gongs1]);
         M('seller')->where('store_id='.$v['store_id'])->setField(['seller_name'=>$gongs[0]]);
         M('store')->where('store_id='.$v['store_id'])->setField(['seller_name'=>$gongs[0]]);
     }
 }
 
     public function huany_koudian(){ //重写产品和订单扣点数量 
 	$store_id="98"; //店铺赋值。
 	$koudian=1;
 	M('goods')->where('store_id='.$store_id)->setField([
 		'points'=>$koudian
 	]);
 	
 	$order_ids=M('order')->where('store_id='.$store_id.' and add_time>1631808000 and add_time<1631980740')->getField('order_id',true);
 		$map['order_id']=['in',$order_ids];
 		
 		$order_goods=M('order_goods')->where($map)->setField([
 		'points'=>$koudian
 	]);
 		\print_r($order_goods); 
 		
     }
    public function index(){
        $this->pushVersion();
        $act_list = session('act_list');
        $menu_list = getMenuList($act_list);
        $this->assign('menu_list',$menu_list);
        $admin_info = getAdminInfo(session('admin_id'));
		$order_amount = M('order')->where("order_status=0 and (pay_status=1 or pay_code='cod')")->count();
		$this->assign('order_amount',$order_amount);
		$this->assign('admin_info',$admin_info);
        $this->display();
    }
   
    public function welcome(){
		if(I('action')=='dida'){
			echo 'yes load.';exit;
		}
    	$this->assign('sys_info',$this->get_sys_info());
    	$today = strtotime("-1 day");
    	$count['handle_order'] = M('order')->where("order_status=0 and (pay_status=1 or pay_code='cod') and fenbu_id=".session('fenbu_id'))->count();//待处理订单
    	$count['new_order'] = M('order')->where("add_time>$today")->count();//今天新增订单
    	$count['goods'] =  M('goods')->where("fenbu_id=".session('fenbu_id'))->count();//商品总数
    	$count['spec'] =  M('spec_goods_price s')->join('ty_goods g on g.goods_id = s.goods_id')
    	->where("g.fenbu_id=".session('fenbu_id'))
    	->count();//商品总数
    	$count['article'] =  M('article')->where("1=1")->count();//文章总数
    	$count['users'] = M('users')->where("1=1 and fenbu_id=".session('fenbu_id'))->count();//会员总数
    	$count['today_login'] = M('users')->where("last_login>$today")->count();//今日访问
    	$count['new_users'] = M('users')->where("reg_time>$today")->count();//新增会员
    	$count['comment'] = M('comment')->where("is_show=0")->count();//最新评论
    	$count['store'] = M('store')->where("fenbu_id=".session('fenbu_id'))->count();//店铺审核
    	$count['bind_class'] = M('store_bind_class')->where("state=0")->count();//申请经营类目
    	$count['brand'] = M('brand')->where("status=0 and store_id>0")->count();//申请品牌
    	$this->assign('count',$count);
        $this->display();
    }
    
    public function get_sys_info(){
		$sys_info['os']             = PHP_OS;
		$sys_info['zlib']           = function_exists('gzclose') ? 'YES' : 'NO';//zlib
		$sys_info['safe_mode']      = (boolean) ini_get('safe_mode') ? 'YES' : 'NO';//safe_mode = Off		
		$sys_info['timezone']       = function_exists("date_default_timezone_get") ? date_default_timezone_get() : "no_timezone";
		$sys_info['curl']			= function_exists('curl_init') ? 'YES' : 'NO';	
		$sys_info['web_server']     = $_SERVER['SERVER_SOFTWARE'];
		$sys_info['phpv']           = phpversion();
		$sys_info['ip'] 			= GetHostByName($_SERVER['SERVER_NAME']);
		$sys_info['fileupload']     = @ini_get('file_uploads') ? ini_get('upload_max_filesize') :'unknown';
		$sys_info['max_ex_time'] 	= @ini_get("max_execution_time").'s'; //脚本最大执行时间
		$sys_info['set_time_limit'] = function_exists("set_time_limit") ? true : false;
		$sys_info['domain'] 		= $_SERVER['HTTP_HOST'];
		$sys_info['memory_limit']   = ini_get('memory_limit');		
        $sys_info['version']   	    = file_get_contents('./Application/Admin/Conf/version.txt');
		$mysqlinfo = M()->query("SELECT VERSION() as version");
		$sys_info['mysql_version']  = $mysqlinfo['version'];
		if(function_exists("gd_info")){
			$gd = gd_info();
			$sys_info['gdinfo'] 	= $gd['GD Version'];
		}else {
			$sys_info['gdinfo'] 	= "未知";
		}
		return $sys_info;
    }
    
    
    public function pushVersion()
    {            
        if(!empty($_SESSION['isset_push']))
            return false;    
        $_SESSION['isset_push'] = 1;    
        error_reporting(0);//关闭所有错误报告
        $app_path = dirname($_SERVER['SCRIPT_FILENAME']).'/';
        $version_txt_path = $app_path.'/Application/Admin/Conf/version.txt';
        $curent_version = file_get_contents($version_txt_path);

        $vaules = array(            
                'domain'=>$_SERVER['SERVER_NAME'], 
                'last_domain'=>$_SERVER['SERVER_NAME'], 
                'key_num'=>$curent_version, 
                'install_time'=>INSTALL_DATE,
                'serial_number'=>SERIALNUMBER,
         );     
         $url = "http://v1.weixinfenxiaoshop.com/index.php?m=Home&c=Index&a=user_push&".http_build_query($vaules);
         stream_context_set_default(array('http' => array('timeout' => 3)));
        file_get_contents($url);         
    }
    
    /**
     * ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
     * table,id_name,id_value,field,value
     */
    public function changeTableVal(){  
            $table = I('table'); // 表名
            $prom = I('prom'); // 表名
            $id_name = I('id_name'); // 表主键id名
            $id_value = I('id_value'); // 表主键id值
            $field  = I('field'); // 修改哪个字段
            $value  = trim(I('value')); // 修改字段值
            if($prom){
                $value .= '&prom=1';
            }
            M($table)->where("$id_name = $id_value")->save(array($field=>$value)); // 根据条件保存修改的数据
            
            if($field == 'getorder'){ //取货时间
                M('return_goods')->where("$id_name = $id_value")->save(array('getorder_time'=>date('Y-m-d H:i:s',time())));
            }
            if($field == 'points'){//扣点
                adminLog('产品id:'.$id_value.'扣点被改成了'.$value);
            }
    }
    public function changeTableVals(){
        $table = I('table'); // 表名
        $id_name = I('id_name'); // 表主键id名
        $id_value = I('id_value'); // 表主键id值
        $field  = I('field'); // 修改哪个字段
        $value  = trim(I('value')); // 修改字段值
        if($field == 'start_time' || $field == 'end_time'){
            $value = strtotime($value);
        }
        M($table)->where("$id_name = $id_value")->save(array($field=>$value)); // 根据条件保存修改的数据
    }
        /**
     * 修改商家结算金额
     * */
    public function changeTableValss(){
        $id = I('id_value');
        $value  = I('value'); //
       //查出这个账单
        $withdrawalsInfo = M('store_withdrawals')
            ->where(['id'=>$id])
            ->order('id desc')
            ->find();
        if(!empty($withdrawalsInfo)){
            //计算要扣除的金额
            if($withdrawalsInfo['expenses'] > $value){
                $withdrawalsInfo['yf_money'] = geshi($withdrawalsInfo['yf_money'] + ($withdrawalsInfo['expenses']-$value));
            }else{
                $withdrawalsInfo['yf_money'] = geshi($withdrawalsInfo['yf_money'] - ($value-$withdrawalsInfo['expenses']));
            }
            // dump($withdrawalsInfo['yf_money']);
            M('store_withdrawals')
                ->where(['id'=>$id])
                ->save([
                    'expenses'=>$value,
                    'yf_money'=>$withdrawalsInfo['yf_money']
                ]); // 根据条件保存修改的数据
        }
    }
    public function store_yijia(){
        $store_id = I('store_id'); // 表名
        $value = I('value'); // 表名
        $fenbu=M('fenbu')->select();

        $quyu_yijia='';
        foreach($fenbu as $v){
            $quyu_yijia.='{"id":"'.$v['fenbu_id'].'","hl":"'.$value.'"},';
        }
        $quyu_yijia='['.rtrim($quyu_yijia, ',').']';
        M('store')->where("store_id = $store_id")->save(array('store_yijia'=>$value,'yijia_quyu'=>$quyu_yijia));
        $quyu_yijia=$value==0 ? null : $quyu_yijia;
        M('goods')->where("store_id = $store_id")->save(array('yijia_quyu'=>$quyu_yijia)); // 根据条件保存修改的数据
    }



}